use crate::http::server::error::Error;
use crate::http::server::handler::result::IntoJsonResponseResult;
use crate::http::server::middleware::ValidatedJson;
use crate::{controller, dto};
use axum::Json;
use axum::extract::State;
use std::sync::Arc;

pub struct AuthHandler {
    controller_set: Arc<controller::ControllerSet>,
}

impl AuthHandler {
    pub fn new(controller_set: Arc<controller::ControllerSet>) -> Self {
        Self { controller_set }
    }

    pub async fn login_apply(
        State(state): State<Arc<Self>>,
        request: ValidatedJson<dto::auth::LoginApplyRequest>,
    ) -> Result<Json<wanmesh_common::dto::Response<dto::auth::LoginResponseData>>, Error> {
        state
            .controller_set
            .auth
            .login_apply(&request.0)
            .await
            .into_json_response_result()
    }

    pub async fn login_submit(
        State(state): State<Arc<Self>>,
        request: ValidatedJson<dto::auth::LoginSubmitRequest>,
    ) -> Result<Json<wanmesh_common::dto::Response<dto::auth::Token>>, Error> {
        state
            .controller_set
            .auth
            .login_submit(&request.0)
            .await
            .into_json_response_result()
    }

    pub async fn refresh_token(
        State(state): State<Arc<Self>>,
        request: ValidatedJson<dto::auth::RefreshTokenRequest>,
    ) -> Result<Json<wanmesh_common::dto::Response<dto::auth::Token>>, Error> {
        state
            .controller_set
            .auth
            .refresh_token(&request.0)
            .await
            .into_json_response_result()
    }
}
